/**
 * My simple header template from child directory
 * IPComparator.java - ${projectName} - ${organizationName} - ${inceptionYear}
 */
/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 02.11.13
 * Time: 21:27
 * To change this template use File | Settings | File Templates.
 */
public class IPComparator {

    public COMPARE_RESULT compare(IPv4 address1, IPv4 address2) {
        if (address1.getSuffix()==0 || address2.getSuffix()==0) {
            return COMPARE_RESULT.DISJOINT; //not expected result
        }
        if (comparePrefixes(address1, address2)) {
            if (address1.getSuffix() == address2.getSuffix()) return COMPARE_RESULT.EQUAL;
            if (address1.getSuffix() < address2.getSuffix()) return COMPARE_RESULT.SUPERSET;
            else return COMPARE_RESULT.SUBSET;
        }
        return COMPARE_RESULT.DISJOINT;
    }

    public boolean comparePrefixes(IPv4 address1, IPv4 address2) {
        int minSuffix = address1.getSuffix()<address2.getSuffix()?address1.getSuffix():address2.getSuffix();
        int shift = 32 - minSuffix;
        return (address1.getBinaryRepresentation() >> shift)==(address2.getBinaryRepresentation() >> shift);
    }

    public enum COMPARE_RESULT {EQUAL, SUBSET, SUPERSET, DISJOINT}
}
